package csd.wyaiyr.com.utils;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Random;

public class StringUtil {

    /**
     * 字符串截取, 去除最后一位
     *
     * @param str
     * @return 截取掉最后一位字符的字符串
     */
    public static String subLastOneStr(String str) {
        str = str.substring(0, str.length() - 1);
        return str;
    }

    /**
     * 字符编码转换成utf8
     *
     * @param txt
     * @return UTF-8编码的字符串
     */
    public static String toUtf8(String txt) {
        try {
            return new String(txt.getBytes("ISO-8859-1"), "UTF-8");
        } catch (Exception e) {
        }
        return "";
    }

    /**
     * 把str 字符编码转换成UTF-8
     * 把[a, b, c]形式的字符串 转换成a,b,c形式
     *
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String changeString(String str) throws UnsupportedEncodingException {
        String newStr = new String(str.getBytes("ISO-8859-1"), "UTF-8").replace(" ", "");
        return newStr.substring(1, newStr.length() - 1);

    }

    /**
     * 判断字符串是否为空 -- null/""/"null"
     *
     * @param str 要判断的字符串
     * @return true 字符串为null/""/"null" false 字符串不为空
     */
    public static boolean isEmpty(String str) {
        if (str == null || "".equals(str.trim()) || "null".equals(str) || "undefined".equals(str)) {
            return true;
        }
        return false;
    }

    public static boolean isEmpty(Date date) {
        if (date == null) {
            return true;
        }
        return false;
    }

    /**
     * 字符数组转化为字符串
     *
     * @param strs   字符数组
     * @param symbol 分隔符
     * @return
     */
    public static String arrayToStr(String[] strs, String symbol) {
        return getString(strs, symbol);
    }

    private static String getString(String[] strs, String symbol) {
        if (strs == null || strs.length == 0) {
            return null;
        }
        if (symbol == null) {
            symbol = "";
        }
        StringBuilder sb = new StringBuilder();
        for (String str : strs) {
            if (sb.length() > 0) {
                sb.append(symbol);
            }
            sb.append(str);
        }
        return sb.toString();
    }
    public static boolean isNotNullAndEmptyByTrim(String str)
    {
        return (str != null) && (!str.trim().equals(""));
    }

    /**
     * 字符串随机位置字符转大写
     * @param oldStr
     * @return
     */
    public static String sjCharToUpperCase(String oldStr){
        if(null == oldStr || oldStr.trim().length() == 0){
           return null ;
        }
        StringBuilder sb = new StringBuilder(oldStr.trim());
        for (int s = 0; s < oldStr.length()/2; s++) {
            int index = new Random().nextInt(oldStr.length() - 1);
            sb.setCharAt(index, Character.toUpperCase(sb.charAt(index)));
        }
        return sb.toString();
    }
}
